package com.tianhui.consignortwofei.mvp.ui.activity;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.pictureSelector.GlideEngine;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseDataListActivity;
import com.tianhui.consignortwofei.constant.Config;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.QuotationListBean;
import com.tianhui.consignortwofei.mvp.ui.adapter.QuotationListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2021/8/10
 * @description
 */
public class QuotationListActivity extends BaseDataListActivity {

    @BindView(R.id.layout_search_editText)
    AutoCompleteTextView searchEditText;

    @BindView(R.id.ll_search_body)
    LinearLayout ll_search_body;

    private DriverModel driverModel;

    private String mSearchKey;
    private boolean firstGo=true;
    private int lookType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_quotation_list;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new QuotationListAdapter(getContext(),lookType);
    }

//    private void setResult(DriverInfo driverInfo) {
//        Intent intent = new Intent();
//        intent.putExtra(KeyValue.KEY_NAME, driverInfo.drivername);
//        intent.putExtra(KeyValue.KEY_PHONE, driverInfo.drivertel);
//        intent.putExtra(KeyValue.KEY_VEHICLE_NUMBER, driverInfo.defaultvehiclenum);
//        setResult(KeyValue.KEY_RESULT_CODE, intent);
//        finish();
//    }

    @Override
    public void initListener() {
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
//                goQuotationDetail(position);
                List<QuotationListBean.QuotationRecords> list =mAdapter.getAllData();
                List<LocalMedia> selectList =new ArrayList<>();
                LocalMedia media=new LocalMedia();
                media.setFileName("internet");
                media.setPath(Config.baseImageUrl+list.get(position).getImgpicture());
//                    media.setCutPath(quotationListDTO.getPicture());
                selectList.add(media);
                // 预览图片 可自定长按保存路径
                PictureSelector.create(QuotationListActivity.this)
                        .themeStyle(com.fgs.common.R.style.picture_default_style) // xml设置主题
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                        .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                        .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .openExternalPreview(0, selectList);


            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                switch (view.getId()){
                    case R.id.tv_xiugai:
                        goQuotationDetail(position);
                        break;
                    case R.id.tv_shanchu:
                        deleteDiaLog(position);

                        break;
                }
            }
        });

    }




    private void goQuotationDetail(int position) {
        QuotationListBean.QuotationRecords driverInfo = (QuotationListBean.QuotationRecords) mAdapter.getAllData().get(position);
        Gson gson=new Gson();
        String json = gson.toJson(driverInfo);
        Bundle bundle=new Bundle();
        bundle.putString("quatationDetail",json);
        bundle.putInt("lookType",lookType);
        openActivity(AddQuotationDetailActivity.class, bundle);

    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        mSearchKey = searchEditText.getText().toString();
//        if (checkSearchKey(mSearchKey)) {

        requestDriverList(mSearchKey, isDialog,page);

//        } else {
//            stopRefresh();
//        }
    }

    @Override
    public void initData() {
        setTitle("报价列表");

        driverModel=new DriverModel();

        Bundle bundle = getIntent().getExtras();
        lookType = bundle.getInt("lookType",2);
        if (1==lookType){
            setSubTitle("添加");
            ll_search_body.setVisibility(View.GONE);
        }

        searchEditText.setHint("请输入报价人");

    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    @Override
    public void onSubtitleClick() {
        Bundle bundle=new Bundle();
        bundle.putInt("lookType",lookType);
        openActivity(AddQuotationDetailActivity.class,bundle);

//        openActivity(PaiHaoActivity.class);
    }



    @OnClick(R.id.layout_search_textView)
    public void searchDriverDetail() {
        mSearchKey = searchEditText.getText().toString();
//        if (checkSearchKey(mSearchKey)) {
            setRefresh(true);
            requestDriverList(mSearchKey, true,1);
//        }
    }

//    private boolean checkSearchKey(String searchKey) {
//        if (TextUtils.isEmpty(searchKey)) {
//            showEmptyView();
//        } else if (CheckUtil.isMobileNO(mSearchKey)) {
//            return true;
//        } else {
//            showToast("请输入正确的手机号");
//        }
//        return false;
//    }


    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);

        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_BAOJIA_LIST:
                setRefresh(true);
                requestDataList(1,true);
                break;
        }
    }

    public void requestDriverList(String phone, boolean isDialog,int page) {
        Map<String, String> map = new HashMap<>();
        map.put("page", page+"");
        map.put("limit", "15");
        map.put("order", "desc");
        map.put("sort", "create_time");
        if (2==lookType){

//            map.put("name", phone);//牌号
//            map.put("warehouse", phone);//库房
//            map.put("ownership", phone);//货权

            map.put("username", phone);
            map.put("status", "1");
        }
        driverModel.getQuotationList(this, map, isDialog, bindLifecycle(), new ObserverResponseListener<CommonResponse<QuotationListBean>>() {
            @Override
            public void onNext(CommonResponse<QuotationListBean> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<QuotationListBean.QuotationRecords> list = commonResponse.getData().getRecords();
//                        List<QuotationListBean.QuotationRecords> resultList = new ArrayList<>();

                        if (list != null && list.size() > 0) {
//                            setPageInfo(1, 1);
//                            for (DriverInfo info : list) {
//                                if (info.drivertel.equals(phone)) {
//                                    resultList.add(info);
//                                }
//                            }
//                            if (list.size() > 0) {
                                showDataList(list);
//                            } else {
//                                showEmptyView();
//                            }

                        }
                        else {
                            showEmptyView();
                        }

                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }


            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    public void deleteDiaLog(int position) {
        new MaterialDialog.Builder(getContext())
                .content("确定要删除吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        deleteQuotation(position);
                    }
                })
                .show();

    }

    private void deleteQuotation(int position) {
        QuotationListBean.QuotationRecords driverInfo = (QuotationListBean.QuotationRecords) mAdapter.getAllData().get(position);
        Map<String, String> map = new HashMap<>();
        map.put("id", driverInfo.getId()+"");
        driverModel.deleteQuotation(getContext(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    showToast("删除成功");
                    mAdapter.remove(position);
//                  quotationRecords.getPlasticsQuotationList().remove(position);
                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });

    }



}